<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
		<link rel="stylesheet" href="lib/semantic/semantic.min.css" />	
		<link rel="stylesheet" type="text/css" href="css/loginReg.css"/>
		<style type="text/css">
			
		</style>
	</head>

	<body>
		<div id="content">
			<!--头部-->
			<div class="header-title">
	            <div class="title-main"><p><img src="img/main_toptitle.png"></p></div>
	            <div class="title-small"><p><img src="img/main_futitle.png"></p></div>
	        </div>
			<!--登录 开始-->
			<form class="ui form" id="login">
	            <div style="padding:20px 0 20px;text-align: center;">
	                <h3 style="text-align: center;">登  录</h3>
	            </div>
				<div style="padding:15px;">
					<div class="ui grid">
						<div class="sixteen wide column">
							<div class="ui labeled input fluid">
								<div class="ui label">
									账号
								</div>
								<input type="text" placeholder="请输入登录账号" class="username block" name="username" id="username">
							</div>
						</div>
						<div class="sixteen wide column">
							<div class="ui labeled input fluid">
								<div class="ui label">
									密码
								</div>
								<input type="password" placeholder="请输入登录密码" class="userpassword" name="userpassword" id="userpassword">
							</div>
						</div>
						<div class="sixteen wide column">
							<div class="ui labeled input fluid">
								<div class="ui toggle checkbox">
									<input type="checkbox" name="public" class="userfinger">
									<label>开启指纹登录</label>
								</div>
							</div>
						</div>
						<div class="eight wide column fluid">
							<input type="button" class="ui fluid button twitter" value="登录" onclick="loginFunValid()"></input>
						</div>
						<div class="eight wide column fluid">
							<input type="reset" id="login_close" class="ui red fluid button" value="清空">
						</div>
					</div>
				</div>
			</form>
			<!--登录 结束-->
			<!--注册 开始-->
			<form class="ui form" id="reg" style="display:none">
	            <div style="padding:20px 0 20px;text-align: center;">
	                <h3 style="text-align: center;">设备绑定申请</h3>
	            </div>
				<div style="padding:15px;">
					<div class="ui grid"><!--
						<div class="sixteen wide column">
							<div class="ui labeled input fluid">
								<div class="ui label" style="width:90px;text-align: center;">
									工号
								</div>
								<input type="text" placeholder="请输入工号" class="usernum" name="usernum">
							</div>
						</div>-->
						<div class="sixteen wide column">
							<div class="ui labeled input fluid">
								<div class="ui label" style="width:90px;text-align: center;">
									姓名
								</div>
								<input type="text" placeholder="请输入姓名" class="userperson" name="userperson">
							</div>
						</div>
						<div class="sixteen wide column">
							<div class="ui labeled input fluid">
								<div class="ui label" style="width:90px;text-align: center;">
									部门/单位
								</div>
								<input type="text" placeholder="请输入部门/单位" class="userdepart" name="userdepart">
							</div>
						</div>
						<div class="eight wide column fluid">
							<input type="button" class="ui fluid button twitter" value="申请绑定" onclick="regFun()"></input>
						</div>
						<div class="eight wide column fluid">
							<input type="button" id="login_close" class="ui red fluid button" value="返回登录" onclick="showLogin()">
						</div>
					</div>
				</div>
			</form>
			<!--注册 结束-->
			<!--尾部-->
			 <div class="wrapper wrapper-bttom">
                <p>武汉市国土资源和规划信息中心 V1.0</p>
            </div>
		</div>
		
		
		<script type="text/javascript" src="cordova.js"></script>
		<!-- -->

		<script type="text/javascript" src="lib/jquery.min.js"></script>
		<script type="text/javascript" src="lib/layer/mobile/layer.js"></script>
		<script type="text/javascript" src="lib/semantic/semantic.js"></script>
		
		<script type="text/javascript">
		
			//版本号
			var M_VERSION = '1.0';
			
			//设备类型
			var M_DEVICETYPE = 'ios';//android or ios
			
			//设备唯一标识（从手机上获取）
			var M_DEVICEINFO = '';
			var M_DEVICEMODEL = '';
			var M_DEVICEVERSION = '';
			
			var PROXY_URI = "http://117.34.70.42:26060/proxy/proxy.jsp?";
			var MOBILE_SERVICE = PROXY_URI + "http://27.17.26.116:8019/MobileServer.asmx"; //WebService服务地址
            //var MOBILE_SERVICE = "http://192.168.50.93:8917/MobileServer.asmx"; //WebService服务地址

			// 登录
			var loginFunValid;
			var M_LOGIN_URI = MOBILE_SERVICE + "/Login";

			// 注册
			var regFun;
			var M_REGDEVICE_URI = MOBILE_SERVICE + "/RegDevice";

			// 检查版本
			var checkNewVersion;
			var M_CHECKNEWVERSION_URI = MOBILE_SERVICE + "/GetVersion";

			// 检查设备是否绑定
			var checkDevice;
			var M_CHECKDEVICE_URI = MOBILE_SERVICE + "/CheckDevice";

/********************************手机App处理开始****************************/
/***************************************************************************/
//===============
var app = {
	// Application Constructor
	initialize: function() {
		document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
	},
	// deviceready Event Handler
	//
	// Bind any cordova events here. Common events are:
	// 'pause', 'resume', etc.
	onDeviceReady: function() {

		if (M_DEVICETYPE === 'android'){
			M_DEVICEINFO = device.imei;
		}else if (M_DEVICETYPE === 'ios'){
			M_DEVICEINFO = device.uuid;
		}
		
		M_DEVICEMODEL = device.model;
		M_DEVICEVERSION = device.platform + ' ' + device.version;
		
		console.log('M_DEVICEINFO:' + M_DEVICEINFO);
		console.log('M_DEVICEMODEL:' + M_DEVICEMODEL);
		console.log('M_DEVICEVERSION:' + M_DEVICEVERSION);
			
		//初始化登录页面的控值
		
			// 反序列化json字符串为对象
		if(window.localStorage.User){
			var _user = JSON.parse(window.localStorage.User);
			console.log(_user);
			//$('.username').val(_user.UName);
			//$('.userpassword').val(_user.UPwd);
			$('.userfinger').prop('checked', _user.Finger); 
		}
			
		//页面加载完成时调用，检查新版本
		checkNewVersion();
	},
};

//本机指纹是否可用正确回调
function isAvailableSuccess(result) {

	console.log('isAvailableSuccess');
	
	//调取指纹验证界面
	if (M_DEVICETYPE === 'android')
		Fingerprint.show({clientId: "Fingerprint-Demo",clientSecret: "password" }, fpsuccessCallback, fperrorCallback);
	else if (M_DEVICETYPE === 'ios')
		touchid.authenticate(fpsuccessCallback, fperrorCallback, "请验证指纹");
}

//本机指纹是否可用错误回调
function isAvailableError(message) {

	layer.open({
		content: '该设备不支持指纹验证',
		skin: 'msg',
		time: 2 //2秒后自动关闭
	});
}

//指纹验证通过
function fpsuccessCallback() {

	console.log('fpsuccessCallback');
	
    //填充用户名和密码，登录
    if(window.localStorage.User){
        var _user = JSON.parse(window.localStorage.User);
        console.log(_user);
        $('.username').val(_user.UName);
        $('.userpassword').val(_user.UPwd);
    }
    
	//登录成功，界面改变登录状态；
	loginFunValid();
}

//指纹验证不通过
function fperrorCallback(err) {
	layer.open({
		content: '指纹验失败',
		skin: 'msg',
		time: 2 //2秒后自动关闭
	});
}

/**********
登录流程处理
当点击登录时：
****/

//检查已登录指纹状态
function checkFingerLogined() {
	console.log("checkFingerLogined");
	
	if(!window.localStorage.User)
		return false;
		
	var _user = JSON.parse(window.localStorage.User);
	console.log(_user);
		
	if(!_user.Finger || _user.Finger === false) {
		return false;
	} 
	
	if (M_DEVICETYPE === 'android')
		Fingerprint.isAvailable(isAvailableSuccess, isAvailableError);
	else if (M_DEVICETYPE === 'ios')
		touchid.checkSupport(isAvailableSuccess, isAvailableError);

	//返回值说明：true表示已使用指纹登录，不显示登录界面。false则表示未使用指纹登录，显示登录界面。
	return true;

}
//嵌入手机时，这句代码需取消注释，由Android开发操作
app.initialize();

/***************************************************************************/
/********************************手机App处理结束****************************/
/***************************************************************************/

			$(function() {

				checkNewVersion = function() {
				
					layer.closeAll();
					layer.open({
						type: 2,
						shadeClose: false,
						content: "加载中...",
					});
				
					$.ajax({
						type: "POST",
						url: M_CHECKNEWVERSION_URI,
						data: {
							strDevType: M_DEVICETYPE // android or ios
						},
						success: function(response) {
							layer.closeAll();
							var result = JSON.parse(response.firstChild.innerHTML);
							console.log(result);
							if(result.errorCode === '0') { // 表示有新版本的地址前往下载
								var webVersion = parseFloat(result.data.version);
								var localVersion = parseFloat(M_VERSION);
								
								//检查最新版本是否大于本地版本，如果需要升级，则跳转到升级页面
								if (webVersion > localVersion){
									console.log(result.data.url);
									window.open(result.data.url);
								}
								else{
									checkDevice();
								}
							} else {
								// 没有找到最新版本，打印提示信息
								console.log(result.errorMessage);
							}
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							layer.closeAll();
							layer.open({
									content: '发生错误,错误内容:' + textStatus,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
						}
					});
				}

				checkDevice = function() {
				
                    console.log('checkDevice IN');
              
					layer.closeAll();
					
					//检查是否保存为超级用户，如果是超级用户则无需进行设备验证
					if(window.localStorage.User){
						var _user = JSON.parse(window.localStorage.User);
						console.log(_user);
						if(_user.Role === '3'){
							$('.username').val(_user.UName);
							$('.userpassword').val(_user.UPwd);
              
                            console.log('checkDevice ready to login');
							
							//登录成功，界面改变登录状态；
							loginFunValid();
							return;
						}
					}

					layer.open({
						type: 2,
						shadeClose: false,
						content: "加载中...",
					});
				
					$.ajax({
						type: 'POST',
						url: M_CHECKDEVICE_URI,
						data: {
							strDevInfo: M_DEVICEINFO //设备信息
						},
						success: function(response) {
							layer.closeAll();
							var result = JSON.parse(response.firstChild.innerHTML);
							console.log(result);

							// 用于测试工作流程
							// result.errorCode = '2';

							if(result.errorCode === '0') {
								// 设备已绑定,进入登录页,保持当前页面状态
								$('#login').show();
								$('#reg').hide();
								
								//判断是否应该弹出指纹
								checkFingerLogined();
							} else if(result.errorCode === '1') {
								// 设备审批中，提示审核设备
								//window.location.href = "checking.html";
									layer.open({
										content: '管理员正在审核该设备',
										skin: 'msg',
										time: 5 //5秒后自动关闭
									});
							} else if(result.errorCode === '2') {
								// 设备未绑定，进入注册页，切换当前页面显示状态
								$('#login').hide();
								$('#reg').show();
							} else {
								layer.open({
									content: result.errorMessage,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
							}
							
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							layer.closeAll();
							layer.open({
									content: '发生错误,错误内容:' + textStatus,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
						}
					});
				};
				
				//桌面浏览器测试调用
				//checkNewVersion();

				/*
				 * 登录方法实现
				 */
				loginFunValid = function() {
				
					layer.closeAll();

					var _un = $('#username').val();
					var _upw = $('#userpassword').val();

					//为空，则退出判断，提示填写
					if($.trim(_un) == "" || $.trim(_upw) == "") {
						layer.open({
							content: '请填写用户名和密码',
							skin: 'msg',
							time: 4 //2秒后自动关闭
						});
						return;
					}
					
					layer.open({
						type: 2,
						shadeClose: false,
						content: "加载中...",
					});
					
					$.ajax({
						type: "POST",
						url: M_LOGIN_URI,
						data: {
							'name': _un,
							'password': _upw,
							'devInfo': M_DEVICEINFO,
							'phoneModels':M_DEVICEMODEL,
							'systemVersion':M_DEVICEVERSION
						},
						success: function(response) {
							layer.closeAll();
							var result = JSON.parse(response.firstChild.innerHTML);
							console.log(result);

							// 用于测试工作流
							//result.errorCode = '0';
							if(result.errorCode === '0') {
								
								console.log(result.User.FileUrl);
								var _userData = {
									//FileUrl: "http://27.17.26.116:8890/mapInfoconfig_new.xml"
									FileUrl: result.User.FileUrl,
									UName: $.trim(_un),
									UPwd: $.trim(_upw),
									Finger:  $('.userfinger').prop('checked'),
									Role:result.User.Role
								}
								
								// 用于测试登陆后信息
								window.localStorage.User = JSON.stringify(_userData);
								// 登陆成功后保存用户信息
								// window.localStorage.User = result.data.User;
								window.location.href = "main.html";
							}
							else if(result.errorCode === '3') {
								//当前设备与用户不匹配
								// 设备未绑定，进入注册页，切换当前页面显示状态
								$('#login').hide();
								$('#reg').show();
							}							
							else {
								layer.open({
									content: result.errorMessage,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
							}
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							layer.closeAll();
							layer.open({
									content: '发生错误,错误内容:' + textStatus,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
						}
					});
				}

				//绑定设备
				regFun = function() {
				
					layer.closeAll();
				
					//var _usernum = $('.usernum').val();
					var _userperson = $('.userperson').val();
					var _userdepart = $('.userdepart').val();

					//为空，则退出判断，提示填写
					if($.trim(_userperson) == "" || $.trim(_userdepart) == "") {
						layer.open({
							content: '请填写姓名和部门信息',
							skin: 'msg',
							time: 4 //2秒后自动关闭
						});
						return;
					}
					
					layer.open({
						type: 2,
						shadeClose: false,
						content: "加载中...",
					});
					
					$.ajax({
						type: "POST",
						url: M_REGDEVICE_URI,
						data: {
							strUName: _userperson,
							strDep: _userdepart,
							strDevInfo: M_DEVICEINFO,
							phoneModels:M_DEVICEMODEL,
							systemVersion:M_DEVICEVERSION
						},
						success: function(response) {
							layer.closeAll();
							var result = JSON.parse(response.firstChild.innerHTML);
							console.log(result);

							if(result.errorCode === '0') {
								// 申请成功
                           
                                $('#login').show();
                                $('#reg').hide();
                           
								layer.open({
									content: '该设备已经提交管理员审核',
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
							} else {
								// 申请失败
								layer.open({
									content: result.errorMessage,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
							}
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							layer.closeAll();
							layer.open({
									content: '发生错误,错误内容:' + textStatus,
									skin: 'msg',
									time: 4 //2秒后自动关闭
								});
						}
					});
				}
				
				//显示登录
				showLogin  = function() {
					$('#login').show();
					$('#reg').hide();
				}
			});
		</script>
	</body>

</html>
